package com.longtengyuyun.reentrantLock;

import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author ZhaoYunLong
 * @date 2022/3/25
 * @description
 */
public class ReentrantLockCondition04 {

    ReentrantLock reentrantLock = new ReentrantLock();
    Condition consumerCondition = reentrantLock.newCondition();
    Condition producerCondition = reentrantLock.newCondition();

    ArrayBlockingQueue producerData = new ArrayBlockingQueue(10);

    public static void main(String[] args) {
        ReentrantLockCondition04 reentrantLockCondition01 = new ReentrantLockCondition04();
        Consumer consumer = reentrantLockCondition01.new Consumer();
        Producer producer = reentrantLockCondition01.new Producer();
        consumer.start();
        producer.start();
    }

    class Consumer extends Thread{

        @Override
        public void run() {
            consume();
        }

        private void consume() {
            try {
                reentrantLock.lock();
                while (producerData.isEmpty()) {
                    System.out.println("队列空，等待数据");
                    consumerCondition.await();
                }
                producerData.poll();
                producerCondition.signal();
                System.out.println("从队列取走一个元素，队列剩余"+producerData.size()+"个元素");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally{
                reentrantLock.unlock();
            }
        }
    }

    class Producer extends Thread{

        @Override
        public void run() {
            produce();
        }

        private void produce() {
            try {
                reentrantLock.lock();
                while (producerData.size() == 10) {
                    System.out.println("队列满，等待有空余空间");
                    producerCondition.await();
                }
                producerData.offer(1);
                System.out.println("向队列取中插入一个元素，队列剩余空间："+(10-producerData.size()));
                consumerCondition.signal();
            } catch (Exception e){
                e.printStackTrace();
            }
            finally{
                reentrantLock.unlock();
            }
        }
    }
}
